/**
 * 自动将svg文件转换为css文件
 *
 * @param {string} svgPath svg文件路径
 *
 * deno run --allow-read --allow-write auto-convert-to-css.ts
 */

import { walkSync, existsSync } from "https://deno.land/std@0.184.0/fs/mod.ts";

const prefix = `<?xml version="1.0" encoding="utf-8"?>
<svg id="icon" class="icon" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <desc>
        Design by @ yonyou audit: https://www.yonyouaud.com
        2023-04-22
    </desc>
    <defs>
        <style>
            rect, line { shape-rendering: crispEdges; }
            svg .icon { display: none }
            svg .icon:target { display: inline } 
        </style>
    </defs>`;

const suffix = `</svg>`;

export default function convertSvgs(distFile: string): string[] {
  if (!distFile) {
    console.log("请输入输出文件名");
    return [];
  }

  if (existsSync(distFile)) {
    // remove it
    Deno.removeSync(distFile);
  }

  const names: string[] = [];

  const svgPath = ".";

  // 递归读取所有目录 .svg 文件
  const svgFiles = walkSync(svgPath, { maxDepth: 5, exts: [".svg"] });
  // 读取 svg 文件内容
  const svgFieleContents = [];
  for (const f of svgFiles) {
    if (f.isFile) {
      const content = Deno.readTextFileSync(f.path);
      const name = f.name.substring(0, f.name.length - 4);
      names.push(name);
      svgFieleContents.push({ name: name, content });
    }
  }
  const distSvgContents = [];
  distSvgContents.push(prefix);
  svgFieleContents.forEach((item) => {
    const g = `<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="${item.name}" class="icon">`;
    const c = item.content;
    if (!c) return;
    // find content startsWith > and endsWith </svg>
    const matcher = c.match(/>([\s\S]*)<\/svg>/);
    if (matcher?.length) {
      distSvgContents.push(g + matcher[1] + "</g></svg>");
    }
  });
  distSvgContents.push(suffix);
  const distSvgContent = distSvgContents.join("\n");
  Deno.writeTextFileSync(distFile, distSvgContent);
  return names;
}
